package engine.util.texture;

import static org.lwjgl.opengl.GL11.GL_R3_G3_B2;
import static org.lwjgl.opengl.GL11.GL_RGB;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import org.lwjgl.BufferUtils;

public class BMPLoader {

	private BMPLoader() {}
	
	public static RawData getBMP(InputStream input, int fileSize) {
		if(input == null) {
			System.err.println("No input stream in getBMP().");
			return null;
		}
		
		byte[] data = new byte[fileSize];
		
		try {
			input.read(data);
		} catch (IOException e) {
			System.err.println("Error while reading header in .bmp");
			return null;
		}
		
		ByteBuffer dataBuffer = BufferUtils.createByteBuffer(data.length).put(data);
		int offset = dataBuffer.getInt(10);
		int width = dataBuffer.getInt(18);
		int height = dataBuffer.getInt(22);
		short biBitCount = dataBuffer.getShort(28);
		int biCompression = dataBuffer.getInt(30);
		
		if(biCompression != 0) {
			System.err.println("Wrong Bitmap Compression used");
			return null;
		}
		
		ByteBuffer imageData = BufferUtils.createByteBuffer(width * height * biBitCount / 8);
		
		for(int i = 0; i < width * height; i++) {
			for(int j = biBitCount / 8 - 1; j >= 0 ; j--) {
				imageData.put(dataBuffer.get(offset + i * biBitCount / 8 + j));
			}
		}
		
		int srcPixelFormat = 0;
		
		switch(biBitCount / 8) {
		case 3: srcPixelFormat = GL_RGB; break;
		case 1: srcPixelFormat = GL_R3_G3_B2; break;
		default: System.err.println("Wrong bit count"); return null;
		}
		
		return new RawData(width, height, GL_RGB, srcPixelFormat, imageData);
	}
}
